﻿using System;
using System.Collections.Generic;

namespace Dotnet.Utils.Utility.CollectionUtil
{
    public static class ArrayExtension
    {
        /// <summary>
        /// 将一个长数组分割成多个短集合
        /// </summary>
        /// <typeparam name="T">数组类型</typeparam>
        /// <param name="source"></param>
        /// <param name="capacity">数组容量</param>
        /// <returns></returns>
        public static IEnumerable<IEnumerable<T>> Split<T>(this T[] source, int capacity = 1)
        {
            List<T[]> result = new List<T[]>();
            if (source == null || source.Length == 0)
            {
                return result;
            }
            if (capacity < 1)
            {
                throw new ArgumentException("capacity参数无效，值必须大于0。");
            }
            int arrrayCount = source.Length / capacity;

            var surplus = source.Length % capacity;
            if (surplus > 0)
            {
                arrrayCount += 1;
            }
            for (int i = 0; i < arrrayCount; i++)
            {
                T[] array;
                if (surplus > 0 && i == arrrayCount - 1)
                {
                    array = new T[surplus];
                    Array.Copy(source, i * capacity, array, 0, surplus);
                }
                else
                {
                    array = new T[capacity];
                    Array.Copy(source, i * capacity, array, 0, capacity);
                }
                result.AddRange(new List<T[]>() { array });
            }
            return result;
        }
    }
}